<template>
  <view>
    <topBackGround :backisShow="1"></topBackGround>
    <div class="title">第四步：连接网络</div>
    <view class="container">
        <view>
            <!-- 请输入家里Wifi名称和密码 -->
            <view class="link_content" v-show="state.pageStatus==0">
              <text class="title_tips">请输入家里Wifi名称和密码</text>
              <view class="link_item mt50">
                <text class="link_text">Wifi名称</text>
                <view class="input_content">
                  <input 
                  class="link_ipt" 
                  type="text" 
                  v-model="wifiData.wifiName" 
                  placeholder="请输入要连接的Wifi名称" 
                  placeholder-class="place-holder"
                  @input="watchWifiName"
                  :focus="nameFocus"
                  >
                  <view 
                    v-show="wifiData.wifiName.length"
                    class="del_btn" 
                    @click="emptyInput(0)"
                    ></view>
                </view>
              </view>
              <view class="link_item">
                <text class="link_text">Wifi密码</text>
                <view class="input_content">
                  <input 
                  class="link_ipt" 
                  type="search" 
                  v-model="wifiData.wifiPass" 
                  placeholder="请输入要连接的Wifi密码"  
                  placeholder-class="place-holder"
                  @input="watchWifiPass"
                  :focus="passFocus"
                  >
                  <view 
                    v-show="wifiData.wifiPass.length"
                    class="del_btn" 
                    @click="emptyInput(1)"
                    ></view>
                </view>
              </view>
              <text class="error_tips2" v-show="linkFail">Wifi名称或者密码错误，请重新输入再连接</text>
              <button 
              :disabled="disabled" 
              :style="[{'opacity':(disabled?'0.5':'1')},{'margin-top':(linkFail?'20px':'50px')}]" 
              :class="'linkwifi_btn mt20'" 
              @click="linkwifi">连接网络</button>
            </view>

            <!-- 网络连接中 -->
            <view v-show="state.pageStatus==1">
              <text class="title_black">网络连接中</text>
              <text class="title_tips2">正在连接网络请稍后</text>
              <view class="connecting_con">
                <image class="connect_gif" src="https://tc-nj-brush-od-pub-1324023246.cos.ap-nanjing.myqcloud.com/static/images/connectGif.gif" />
              </view>
            </view>

            <!-- 网络链接失败 -->
            <view v-show="state.pageStatus==2">
              <text class="title_error">网络链接失败</text>
              <text class="title_tips2">暂无信号请点击重新连接网络</text>
              <view class="connect_fail_con">
                <image class="connect_fail" src="../../images/connect_fail.png" />
              </view>
              <button @click="linkagain" type="button" class="main_btn">重新连接网络</button>
            </view>

            <!-- 连接成功 -->
            <view v-show="state.pageStatus==3">
              <text class="title_black">连接成功</text>
              <view class="linkSuccess">
                <cover-image class="sucess_pen" src="../../images/default_pen.png" />
                <text class="success_black">{{ conncetDivece.nickName }}</text>
                <text class="title_tips3 align_left">已成功连接设备，请点击下方「完成连接」按钮结束配置</text>
                <button @click="finishLink" type="button" class="main_btn2">完成连接</button>
              </view>
            </view>
        </view>
    </view>
  </view>
</template>
    
<script setup>
  import topBackGround from '../../../src/components/backGround.vue'
  import { ref, reactive, onMounted, watch } from 'vue'
  import Taro from '@tarojs/taro';
  import { getCurrentInstance as getVueCurrentInstance } from 'vue';
  import requset from '../../network/request';
  import { useBluetoothStore } from '../../store/blueTooth'

  const { 
    state, 
    createBLEConnection,
    buildWifiFrame,
    sendWifiFrameToModule,
    writeBLECharacteristicValue,
    getDeviceStatus,
    string2buffer,
    ab2hex,
    getBLEDeviceServices
  } = useBluetoothStore()

  const wifiLinkStatus = (status) => {
    const statusMessages = {
      0: '没有配置ssid密码',
      1: '没有连接上',
      2: '连接上了',
      3: '连接上服务器'
    }
    return statusMessages[status]
  }

  const userId = Taro.getStorageSync('userId');
  const userToken = Taro.getStorageSync('token');

  const instance = getVueCurrentInstance();
  instance.appContext.config.globalProperties.$loadFontFace()

  let disabled = ref(true)
  let nameFocus = ref(false)
  let passFocus = ref(false)
  // let state.pageStatus    // 0.请输入家里Wifi名称和密码  1.网络连接中 2.网络链接失败 3.网络链接失败
  let linkFail = ref(false)

  const wifiData = reactive({
    wifiName: 'RedmiK70',
    // wifiPass: 'i4season6666-',
    wifiPass: '',
    serve:'yuanchuangjun.moyin.com'
  })

  let conncetDivece = ref({})


  onMounted(() => {
    console.log('获取蓝牙设备的服务 - getBLEDeviceServices')
    console.log( 'state.deviceId:', state.deviceId )
    console.log( 'state.nickName:', state.name )
    // createBLEConnection(state.deviceId, state.name || state.localName)
    if(state.chooseWifiName) {
      wifiData.wifiName = state.chooseWifiName
    }
  })


  // 添加冒号
  function addColons(mac) {
    return mac.match(/.{1,2}/g).join(':');
  }

  watch(()=>state.pageStatus, (value) => {
    if( value === 3 ) {
      // state.mac: 84a56dadae20
      // state.sn: 12345678
      // state.name: 智能毛笔-84a56dadae20
      // state.deviceId: 20:AE:AD:6D:A5:84
      // state.serve: undefined
      // state.serviceId: 00001910-0000-1000-8000-00805F9B34FB
      // state.filterName: Smartpen

      
      console.log('state.deviceId:', state.deviceId)
      console.log('state.mac:', state.mac)
      console.log('state.name:', state.name)
      console.log('state.sn:', state.sn)
      console.log('addColons(state.deviceId):', addColons(state.deviceId))
      
      addDevice(state.sn, state.name, addColons(state.deviceId))
      // addDevice(deviceId, nickName, mac)
    }
  })


  // 连接到 Wi-Fi
  const connectToWifi = async () => {
    if (!ssid.value || !password.value) {
      Taro.showToast({
        title: '请填写完整的Wi-Fi信息',
        icon: 'error',
        duration: 2000
      })
      return
    }

    try {
      await Taro.connectWifi({
        SSID: ssid.value,
        password: password.value
      })
      Taro.showToast({
        title: 'Wi-Fi 连接成功',
        icon: 'success',
        duration: 2000
      })
    } catch (error) {
      Taro.showToast({
        title: `连接失败: ${error.errMsg}`,
        icon: 'error',
        duration: 2000
      })
    }
  }

  // wifi名称
  function watchWifiName() {
    setTimeout(() => {
      console.log (wifiData)
      watchWifiInput()
    },200)
  }
  // wifi密码
  function watchWifiPass() {
    setTimeout(() => {
      console.log (wifiData)
      watchWifiInput()
    },200)
  }

  function watchWifiInput() {
    if( wifiData.wifiName !== '' && wifiData.wifiPass !== '' ){
      disabled.value = false
    } else {
      disabled.value = true
    }
    // console.log('disabled::', disabled)
  }

  function emptyInput(num) {
    if (num === 0) {
      wifiData.wifiName = ''
      nameFocus.value = false
      setTimeout(() =>{
        nameFocus.value = true
      },200)
    } else {
      wifiData.wifiPass = ''
      passFocus.value = false
      setTimeout(() =>{
        passFocus.value = true
      },200)
    }
    disabled.value = true
  }

  // 0: 输入wifi名称与密码阶段
  // 1: 网络链接中
  // 2: 网络链接失败
  function linkwifi() {

    state.pageStatus = 1
    console.log('linkwifi - wifiData.wifiName:', wifiData.wifiName)
    console.log('linkwifi - wifiData.wifiPass:', wifiData.wifiPass)
    sentWifiData()
  }

  // 重新连接网络
  function linkagain() {
    state.pageStatus = 1
    sentWifiData()
  }

  // 发送wifi数据
  function sentWifiData() {
    // wifi连接 构建数据帧
    const frame = buildWifiFrame(wifiData.wifiName, wifiData.wifiPass, wifiData.serve);
    console.log("构建的数据帧：", frame);
    // wifi连接 分包并发送构建好的数据帧
    sendWifiFrameToModule(frame);
  }

  // 完成连接
  function finishLink() {
    Taro.setStorage({
      key:"conncetDivice",
      data: {
        deviceId: state.deviceId,
        nickName: state.name
      }
    })
    state.index = 0
    state.pageStatus = 0
    Taro.switchTab({
      url: `/pages/offering/index`
    })
    state.fromPage = 'linkwifi'
  }

  function addDevice(deviceId, nickName, mac) {
    requset('/mini-program/device/bind', {
      method: 'post',
        data: {
          userId,
          userToken,
          deviceId,
          nickName,
          mac
        }
    }).then(res =>{
      // console.log(res)
      if ( res.code === 200 ) {
        Taro.setStorage({
          key:"isAddDeivce",
          data: true
        })
        state.pageStatus = 3
        state.isFinishWifiList = false
        state.wifiList = []
        state.penListData = []
      } else if(res.code === 5002){   /// 设备已被其他人绑定
        Taro.showToast({
          title: '设备已被其他人绑定',
          icon: 'error',
          duration: 3000,
          success(){
            const timer = setTimeout(function() {
              Taro.switchTab({
                url: `/pages/offering/index`
              })
            },1000)
          }
        })
      } else {
        Taro.showToast({
          title: res.msg,
          icon: 'error',
          duration: 3000,
          success(){
            const timer = setTimeout(function() {
              Taro.navigateTo({
                // url: `/pages/match/index`
              })
            },1000)
          }
        })
      }
    })
  }
  </script>
  
  <style>
  .link_content{
    width: 90%;
    margin: 0 auto;
  }

  .link_item {
    margin-bottom: 40px;
  }

  .link_text {
    font-family: 'siyuan',sans-serif;
    font-size: 40px;
    color: #181410;
  }

  .link_ipt {
    width: 100%;
    height: 112px;
    background: #FFF;
    border: #E9DECA 1px solid;
    border-radius: 20px;
    margin-top: 20px;
    padding: 0 40px;
    box-sizing: border-box;
  }

  .place-holder {
    color: #C3B3A0;
    font-size: 40px;
  }

  .linkwifi_btn {
    width: 670px;
    height: 112px;
    line-height: 112px;
    font-size: 40px;
    color: #FFF;
    text-align: center;
    background-color: #956F31;
    display: block;
    margin: 96px auto 0 auto;
    border-radius: 100px;
    opacity: .5;
  }
  
  .opacity1{
    opacity: 1;
  }

  .input_content{
    position: relative;
  }

  .del_btn{
    width: 48px;
    height: 48px;
    background-color: red;
    background: url('../../images/del_btn.png') no-repeat;
    background-size: cover;
    position: absolute;
    top:32px;
    right: 32px;
    z-index: 3;
    display: block;
  }

  .linkSuccess{
    width: 80%;
    margin: 50px auto;
    height: 664px;
    background-color: #FFF;
    border-radius: 20px;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: space-around;
    padding: 30px;
    box-sizing: border-box;
  }

  .sucess_pen {
    width: 216px;
    height: 216px;
  }

  .connecting_con, .connect_fail_con {
    width: 100%;
    height: 300px;
    text-align: center;
    margin-top: 160px;
  }
  .connect_gif, .connect_fail {
    width: 300px;
    height: 220px;
  }

  </style>